package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.bill.model.enums.OrderSourceEnum;
import com.wing.common.constant.SecurityConstants;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.model.entity.*;
import com.wing.product.model.request.*;
import com.wing.product.model.response.*;
import com.wing.web.utils.JwtUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.product.dao.WarehouseShipmentOrderDao;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WarehouseShipmentOrderServiceImpl extends ServiceImpl<WarehouseShipmentOrderDao, WarehouseShipmentOrder> implements WarehouseShipmentOrderService{


    @Autowired
    private WarehouseShipmentOrderDetailService warehouseShipmentOrderDetailService;

    @Autowired
    private WarehouseOrderService warehouseOrderService;

    @Autowired
    private WarehouseOrderDetailService warehouseOrderDetailService;


    @Autowired
    private WarehouseProductInventoryService warehouseProductInventoryService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(WarehouseShipmentOrderForm warehouseShipmentOrderForm) {
        for ( WarehouseShipmentOrderDetailForm orderDetailForm1 : warehouseShipmentOrderForm.getWarehouseShipmentOrderDetail()) {
             String kb =orderDetailForm1.getUserBundleDetail();
            List<Map> list=baseMapper.findByUserKB(kb);
            if(list.size()>0){
                return false;
            }
        }

        WarehouseShipmentOrder warehouseShipmentOrder = new WarehouseShipmentOrder();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseShipmentOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseShipmentOrderForm, warehouseShipmentOrder,copyOptions);
        warehouseShipmentOrder.setOrderCode(warehouseShipmentOrderForm.getOrderCode());
        warehouseShipmentOrder.setShipmentOrderCode(UniqueIdGeneratorUtil.generateUniqueId("FH", "yyyyMMddHHmmss", 1000, 9999));
//        Double sum = 0d;
//        List<WarehouseOrderDetail> warehouseOrderDetailList=new ArrayList<WarehouseOrderDetail>();
//
//        for (WarehouseShipmentOrderDetailForm warehouseShipmentOrderDetailForm : warehouseShipmentOrderForm.getWarehouseShipmentOrderDetail()) {
//            Double quantity = warehouseShipmentOrderDetailForm.getQuantity();
//            sum += quantity;
//            WarehouseOrderDetail warehouseOrderDetail=warehouseOrderDetailService.findByOrderDetailCode(warehouseShipmentOrderDetailForm.getOrderDetailCode());
////            warehouseOrderDetail.setRemainingQuantity(warehouseOrderDetail.getRemainingQuantity()-warehouseShipmentOrderDetailForm.getUserBundleDetail().size());
//            warehouseOrderDetailList.add(warehouseOrderDetail);
//        }
//        warehouseOrderDetailService.updateBatchById(warehouseOrderDetailList);

//        warehouseShipmentOrder.setTotalQuantity(sum);

        // 查询出托管订单托管总数减去当前发货数量
//        WarehouseOrder warehouseOrder=warehouseOrderService.findByOrderCode(warehouseShipmentOrderForm.getOrderCode());
//        if(warehouseOrder.getTotalWeight()<sum){
//            return false;
//        }
        //修改托管订单的数量
//        warehouseOrder.setTotalQuantity(warehouseOrder.getTotalQuantity()-sum);
//        warehouseOrderService.updateById(warehouseOrder);
        //2025年4月2日 20:24:03 prz 上面已经更新了订单的库存，如果再减就是脏数据
//        warehouseShipmentOrder.setRemainder(warehouseOrder.getTotalQuantity()-sum);
//        warehouseShipmentOrder.setRemainder(warehouseOrder.getTotalQuantity());
        //修改数据来源改为前端传值
//        warehouseShipmentOrder.setSource(warehouseShipmentOrderForm.getSource());
//        if(JwtUtils.getClientId().equals(SecurityConstants.ADMIN_CLIENT_ID)) {
//            warehouseShipmentOrder.setSource(OrderSourceEnum.PLATFORM.getCode());
//        }
//        if(JwtUtils.getClientId().equals(SecurityConstants.WAREHOUSE_CLIENT_ID)) {
//            warehouseShipmentOrder.setSource(OrderSourceEnum.CUSTOMER.getCode());
//        }
        warehouseShipmentOrder.setShipmentOrderStatus(1);
        baseMapper.insert(warehouseShipmentOrder);


        List<WarehouseProductInventory> inventoryList = new ArrayList<>();
        for ( WarehouseShipmentOrderDetailForm orderDetailForm : warehouseShipmentOrderForm.getWarehouseShipmentOrderDetail()) {
            WarehouseShipmentOrderDetail warehouseShipmentOrderDetail = new WarehouseShipmentOrderDetail();
            CopyOptions copyDetailOptions = CopyOptions.create()
                    .setEditable(WarehouseShipmentOrderDetail.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(orderDetailForm, warehouseShipmentOrderDetail, copyDetailOptions);
            warehouseShipmentOrderDetail.setWarehouseProductId(orderDetailForm.getProductDetailId());
            warehouseShipmentOrderDetail.setShipmentOrderId(warehouseShipmentOrder.getId());
            warehouseShipmentOrderDetail.setShipmentOrderCode(warehouseShipmentOrder.getShipmentOrderCode());
            warehouseShipmentOrderDetail.setOrderCode(warehouseShipmentOrder.getOrderCode());
            warehouseShipmentOrderDetail.setOrderId(warehouseShipmentOrder.getOrderId());
//            warehouseShipmentOrderDetail.setTotalQuantity(Double.parseDouble(orderDetailForm.getQuantity()));
            warehouseShipmentOrderDetail.setTotalPrice(orderDetailForm.getPrice());
            warehouseShipmentOrderDetail.setTotalWeight(orderDetailForm.getTotalWeight());
            warehouseShipmentOrderDetail.setProductUnitId(orderDetailForm.getProductMainUnitId());
            warehouseShipmentOrderDetail.setWarehouseProductCode(orderDetailForm.getProductCode());
//            warehouseShipmentOrderDetailService.save(warehouseShipmentOrderDetail);

            //添加产品明细
            WarehouseProductInventory warehouseProductInventory = new WarehouseProductInventory();
            warehouseProductInventory.setWarehouseOrderId(Long.parseLong(warehouseShipmentOrderForm.getOrderId()));//合同id
            warehouseProductInventory.setWarehouseShipmentOrderId(warehouseShipmentOrder.getId());//发货订单id
            warehouseProductInventory.setCustomerId(warehouseShipmentOrder.getCustomerId());//所属客户id
            warehouseProductInventory.setOriginalCustomerId(warehouseShipmentOrder.getCustomerId());//原始客户id
            warehouseProductInventory.setQuantity(orderDetailForm.getQuantity());//数量
            warehouseProductInventory.setPrice(warehouseShipmentOrderDetail.getPrice());//价格
            warehouseProductInventory.setNetWeight(warehouseShipmentOrderDetail.getNetWeight());//净重
            warehouseProductInventory.setGrossWeight(warehouseShipmentOrderDetail.getGrossWeight());//毛重
            warehouseProductInventory.setUserBundleCode(warehouseShipmentOrderDetail.getUserBundleDetail());//用户捆包号
            warehouseProductInventory.setSysBundleCode(UniqueIdGeneratorUtil.generateUniqueId("BC-", "yyyyMMddHHmmss", 1000, 9999));
            warehouseProductInventory.setProductMainUnitId(orderDetailForm.getProductMainUnitId());//单位id
            warehouseProductInventory.setSpecifications(orderDetailForm.getProductSpecCode());//规格码
            warehouseProductInventory.setProduct_producer_id(Integer.parseInt(orderDetailForm.getProductProducerId()));//产地
            warehouseProductInventory.setWarehouseProductVariety(orderDetailForm.getProductVarietyId());//品种
            warehouseProductInventory.setProductType(4);//物资类型
            warehouseProductInventory.setSpecLength(orderDetailForm.getLength());
            warehouseProductInventory.setSpecWidth(String.valueOf(orderDetailForm.getWidth()));
            warehouseProductInventory.setSpecThickness(String.valueOf(orderDetailForm.getThickness()));
            warehouseProductInventory.setWarehouseProductMark(orderDetailForm.getProductMarkId());
//            warehouseProductInventoryService.save(warehouseProductInventory);
            inventoryList.add(warehouseProductInventory);
        }
        warehouseProductInventoryService.saveBatch(inventoryList);

        return true;
    }

    @Override
    public Boolean update(WarehouseShipmentOrderForm warehouseShipmentOrderForm) {
//        WarehouseShipmentOrder warehouseShipmentOrder = new WarehouseShipmentOrder();
//        CopyOptions copyOptions = CopyOptions.create()
//                .setEditable(WarehouseShipmentOrder.class)
//                .setIgnoreError(true)
//                .setIgnoreNullValue(true);
//        BeanUtil.copyProperties(warehouseShipmentOrderForm, warehouseShipmentOrder,copyOptions);
//        warehouseShipmentOrder.setId(warehouseShipmentOrderForm.getId());
//        warehouseShipmentOrder.setShipmentOrderCode(UniqueIdGeneratorUtil.generateUniqueId("FH", "yyyyMMddHHmmss", 1000, 9999));
//        Double sum = 0d;
//        for (WarehouseShipmentOrderDetailForm warehouseShipmentOrderDetailForm : warehouseShipmentOrderForm.getWarehouseShipmentOrderDetail()) {
//            Double quantity = warehouseShipmentOrderDetailForm.getQuantity();
//            sum += quantity;
//        }
//        warehouseShipmentOrder.setTotalQuantity(sum);
//        if(JwtUtils.getClientId().equals(SecurityConstants.ADMIN_CLIENT_ID)) {
//            warehouseShipmentOrder.setSource(OrderSourceEnum.PLATFORM.getCode());
//        }
//        if(JwtUtils.getClientId().equals(SecurityConstants.WAREHOUSE_CLIENT_ID)) {
//            warehouseShipmentOrder.setSource(OrderSourceEnum.CUSTOMER.getCode());
//        }
//        warehouseShipmentOrder.setShipmentOrderStatus(1);
//        baseMapper.updateById(warehouseShipmentOrder);
//
//
////        List<WarehouseProductInventory> inventoryList = new ArrayList<>();
//        for ( WarehouseShipmentOrderDetailForm orderDetailForm : warehouseShipmentOrderForm.getWarehouseShipmentOrderDetail()) {
//            WarehouseShipmentOrderDetail warehouseShipmentOrderDetail = new WarehouseShipmentOrderDetail();
//            CopyOptions copyDetailOptions = CopyOptions.create()
//                    .setEditable(WarehouseShipmentOrderDetail.class)
//                    .setIgnoreError(true)
//                    .setIgnoreNullValue(true);
//            BeanUtil.copyProperties(orderDetailForm, warehouseShipmentOrderDetail,copyDetailOptions);
//            warehouseShipmentOrderDetail.setId(orderDetailForm.getId());
//            warehouseShipmentOrderDetail.setWarehouseProductId(orderDetailForm.getProductDetailId());
//            warehouseShipmentOrderDetail.setShipmentOrderId(warehouseShipmentOrder.getId());
//            warehouseShipmentOrderDetail.setShipmentOrderCode(warehouseShipmentOrder.getShipmentOrderCode());
//            warehouseShipmentOrderDetail.setOrderCode(warehouseShipmentOrder.getOrderCode());
//            warehouseShipmentOrderDetail.setOrderId(warehouseShipmentOrder.getOrderId());
//            warehouseShipmentOrderDetail.setTotalQuantity(orderDetailForm.getQuantity());
//            warehouseShipmentOrderDetail.setTotalPrice(orderDetailForm.getPrice());
//            warehouseShipmentOrderDetail.setTotalWeight(orderDetailForm.getTotalWeight());
//            warehouseShipmentOrderDetail.setProductUnitId(orderDetailForm.getProductMainUnitId());
//            warehouseShipmentOrderDetail.setWarehouseProductCode(orderDetailForm.getProductCode());
//            warehouseShipmentOrderDetail.setProductVarietyId(orderDetailForm.getProductVarietyId());
//            warehouseShipmentOrderDetailService.save(warehouseShipmentOrderDetail);
//            for(UserBundleDetailForm bundleDetailForm : orderDetailForm.getUserBundleDetail()){
//                WarehouseProductInventory warehouseProductInventory = new WarehouseProductInventory();
//                CopyOptions copyBundleDetailOptions = CopyOptions.create()
//                        .setEditable(WarehouseProductInventory.class)
//                        .setIgnoreError(true)
//                        .setIgnoreNullValue(true);
//                BeanUtil.copyProperties(bundleDetailForm, warehouseProductInventory,copyBundleDetailOptions);
//                warehouseProductInventory.setWarehouseShipmentOrderId(warehouseShipmentOrder.getId());
//                warehouseProductInventory.setCustomerId(warehouseShipmentOrder.getCustomerId());
//                warehouseProductInventory.setOriginalCustomerId(warehouseShipmentOrder.getCustomerId());
//                warehouseProductInventory.setWarehouseShipmentOrderDetailId(warehouseShipmentOrderDetail.getId());
//                warehouseProductInventory.setWarehouseProductId(warehouseShipmentOrderDetail.getWarehouseProductId());
//                warehouseProductInventory.setPrice(warehouseShipmentOrderDetail.getPrice());
//                warehouseProductInventory.setNetWeight(warehouseShipmentOrderDetail.getNetWeight());
//                warehouseProductInventory.setGrossWeight(warehouseShipmentOrderDetail.getGrossWeight());
//                warehouseProductInventory.setSysBundleCode(UniqueIdGeneratorUtil.generateUniqueId("BC-", "yyyyMMddHHmmss", 1000, 9999));
//                inventoryList.add(warehouseProductInventory);
//            }
//        }
//        warehouseProductInventoryService.updateBatchById(inventoryList);
        return true;
    }

    @Override
    public Page<WarehouseShipmentOrderVO> pageList4app(Page page, Map<String, Object> params) {
//        return new PageResult<>(baseMapper.list4app(pg, paramMap));
        List<WarehouseShipmentOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ShipmentOrderInfoVO getInfoByShipmentId(String shipmentOrderId) {
        ShipmentOrderInfoVO shipmentOrderInfoVO = baseMapper.getInfoByShipmentId(shipmentOrderId);
        shipmentOrderInfoVO.setShipmentOrderDetailInfoList(baseMapper.getDetailInfoByShipmentId(shipmentOrderInfoVO.getId()));
        List<Long> detailIds = shipmentOrderInfoVO.getShipmentOrderDetailInfoList().stream().map(ShipmentOrderDetailInfoVO::getId).collect(Collectors.toList());
        List<ShipmentProductInventoryVO> shipmentProductInventoryVO = baseMapper.getInventoryInfoByShipmentId(detailIds);
        processShipmentDetails(shipmentOrderInfoVO.getShipmentOrderDetailInfoList(),shipmentProductInventoryVO);
        return shipmentOrderInfoVO;
    }

    @Override
    public WarehouseShipmentOrderInfoVO findOrderInfoById(Long id ,String type) {
        WarehouseShipmentOrderInfoVO vo =  baseMapper.findOrderInfoById(id);
        vo.setOrderInfoDetail(warehouseOrderDetailService.findOrderDetailListByOrderId(id,type));
        return vo;
    }

    @Override
    public WarehouseShipmentOrderInfoVO info(Long id,String waybill) {
        WarehouseShipmentOrderInfoVO vo =  baseMapper.info(id,waybill);
        vo.setOrderInfoDetail(baseMapper.infoDetail(vo.getId()));
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(Long id, Integer status) {
        // 根据 id 查询订单
//        WarehouseShipmentOrder order = baseMapper.selectById(id);
//        order.setShipmentOrderStatus(status);
//        baseMapper.updateById(order);
         boolean a=baseMapper.updateStatus(id,status);
        // 如果订单不存在，返回失败
//        if(ObjectUtil.isEmpty(order)){
//            return false;
//        }
//        WarehouseOrder wo = warehouseOrderService.getById(order.getOrderId());
//        // 2为受理，修改 托管订单状态 及发货订单状态
//        if(status == 2){
//            order.setShipmentOrderStatus(2);
//            wo.setStatus(4);
//            //0 为驳回 修改发货订单状态，不处理托管订单状态
//        }else if(status == 0){
//            order.setShipmentOrderStatus(0);
//            wo.setStatus(3);
//            //修改托管订单的数量,撤销后给原来的数量加到托管订单上去
//            WarehouseOrder warehouseOrder=warehouseOrderService.findByOrderCode(order.getOrderCode());
//            warehouseOrder.setTotalQuantity(warehouseOrder.getTotalQuantity()+order.getTotalQuantity());
//            warehouseOrderService.updateById(warehouseOrder);
//        }
//        warehouseOrderService.updateById(wo);
//        updateById(order);
        // 设置受理成功
        return a;
    }

    @Override
    public boolean revoke(Long id, Integer status) {
        return baseMapper.updateStatus(id,status);
    }

    private void processShipmentDetails(
            List<ShipmentOrderDetailInfoVO> detailInfoList,
            List<ShipmentProductInventoryVO> inventoryList) {

        // 将 detailInfoList 转为 Map，以 id 为键
        Map<Long, ShipmentOrderDetailInfoVO> detailInfoMap = detailInfoList.stream()
                .collect(Collectors.toMap(ShipmentOrderDetailInfoVO::getId, detailInfo -> detailInfo));

        // 遍历 inventoryList，将每个 inventory 放入对应的 detailInfo 的 List
        for (ShipmentProductInventoryVO inventory : inventoryList) {
            Long orderDetailId = inventory.getWarehouseShipmentOrderDetailId();
            ShipmentOrderDetailInfoVO detailInfo = detailInfoMap.get(orderDetailId);

            if (detailInfo != null) {
                // 如果匹配的 ShipmentOrderDetailInfoVO 存在，添加到其 List 中
                if (detailInfo.getShipmentProductInventoryList() == null) {
                    detailInfo.setShipmentProductInventoryList(new ArrayList<>());
                }
                detailInfo.getShipmentProductInventoryList().add(inventory);
            }
        }
    }
}
